package org.qiyu.live.im.core.server.handler.impl;

import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import org.apache.rocketmq.client.producer.MQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.qiyu.live.im.core.server.common.ImContextUtils;
import org.qiyu.live.im.core.server.common.ImMsg;
import org.qiyu.live.im.core.server.handler.SimpleHandler;
import org.qiyu.live.im.dto.ImMsgBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import static org.qiyu.live.common.interfaces.topic.ImCoreServerProviderTopicNames.QIYU_LIVE_IM_BIZ_MSG_TOPIC;

/**
 * Created with IntelliJ IDEA.
 * Description: 业务handler 主要进行业务处理
 * User: sfx
 * Date: 2023-10-07
 * Time: 16:48
 */
@Component
public class BizMsgHandler implements SimpleHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(BizMsgHandler.class);

    @Resource
    private MQProducer mqProducer;

    private final Logger logger = LoggerFactory.getLogger(BizMsgHandler.class);

    /**
     * 业务处理 :
     * 接收到客户端传来的消息,把消息投递给MQ(Msg-provider层) 然后msg-provider层
     * 进行业务处理后把消息投递给业务下游 -- router层做一下中转(他知道应该发送到哪一台im-core-server机器)
     * im-core-server需要暴露RPC接口供其router层进行调用;
     * 发送到im-core-server机器上之后,这边在转发给客户端
     */
    @Override
    public void handler(ChannelHandlerContext ctx, ImMsg msg) {
        // 1. 对userId, appId 进行校验
        Long userId = ImContextUtils.getUserId(ctx);
        Integer appId = ImContextUtils.getAppId(ctx);
        if (userId == null || appId == null || userId < 10000 || appId < 10000) {
            logger.error("attr error msg={}", msg);
            ctx.close();
            throw new IllegalArgumentException("attr error");
        }

        // 2. 对body进行校验
        byte[] body = msg.getBody();
        if (body == null || body.length == 0) {
            ctx.close();
            logger.error("body error msg={}", msg);
            throw new IllegalArgumentException("body error");
        }
        // 3. 构建Message 利用MQ 传递给业务下游(msg-provider) 进行业务相关处理
        Message message = new Message();
        message.setBody(body);
        message.setTopic(QIYU_LIVE_IM_BIZ_MSG_TOPIC);

        try {
            SendResult sendResult = mqProducer.send(message);
            logger.info("投递消息成功,消息结果为{}", sendResult);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}